from django.shortcuts import render, get_object_or_404
from django.core.mail import send_mail
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Count
from taggit.models import Tag
from .models import Category, Comment, Post
from .forms import EmailPostForm, CommentForm, PostForm


# Create your views here.


def index(request):
    '''我的博客主页'''
    categories = Category.objects.all()
    context = {'categories':categories}
    return render(request, 'blog/index.html', context)


def post_list(request):
    '''我的博文列表'''
    object_list = Post.objects.all()
    paginator = Paginator(object_list, 6)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        #如果页面不是整数，则输出第一页
        posts = paginator.page(1)
    except EmptyPage:
        #如果页面超出范围传递结果的最后一页
        posts = paginator.page(paginator.num_pages)

    context = {'page':page, 'posts':posts}
    return render(request, 'blog/post/list.html', context)


def post_detail(request, post_id):
        post = Post.objects.get(id=post_id)
        comments = post.comments.filter(active=True)
        new_comment = None
        if request.method != 'POST':
            comment_form = CommentForm()
        else :
            comment_form = CommentForm(data=request.POST)
            if comment_form.is_valid():
                new_comment = comment_form.save(commit=False)
                new_comment.post = post
                new_comment.save()
        post_tags_ids = post.tags.values_list('id', flat=True)
        similar_posts = Post.objects.filter(tags__in=post_tags_ids).exclude(id=post.id)
        similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-created')[:4]
        context = {'post':post, 'comments':comments, 'new_comment':new_comment, 'comment_form':comment_form, 'similar_posts':similar_posts}
        return render(request, 'blog/post/detail.html', context)


def post_share(request, post_id):
	post = Post.objects.get(id=post_id)
	sent = False
	if request.method != 'POST':
		form = EmailPostForm()

	else:
		form = EmailPostForm(data=request.POST)
		if form.is_valid():
			cd = form.cleaned_data

			post_url = request.build_absolute_uri(post.get_absolute_url())

			subject = '{} ({}) recommends you reading "{}"'.format(cd['name'], 'xihong_hu@126.com', post.title)

			message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])

			send_mail(subject, message, 'xihong_hu@126.com',[cd['toemail']])
			sent = True

	context = {'post':post, 'form':form, 'sent':sent}
	return render(request, 'blog/post/share.html', context)


def post_add(request):
    '''添加新帖子'''
    return render(request, 'blog/post/add.html',)


def post_sub(request):
    '''保存提交'''
    Post.objects.create(
        title="测试",
        author=request.user,
        slug=1,
        content=request.POST['content'],
        view_count=1,
        comment_count=1,
        status='publish',
    )
    return render(request, 'blog/post/add_sub.html',)


def post_edit(request, post_id):
    '''编辑帖子'''
    post = Post.objects.get(id=post_id)
    context = {'post':post}
    return render(request, 'blog/post/edit.html', context)


def post_del(request, post_id):
    '''删除帖子'''
    Post.objects.get(id=post_id).delete()
    return render(request, 'blog/post/del.html')


